#include "WString.h"
#include "esp32-hal-gpio.h"
#include "Arduino.h"
#include "WiFi.h"
#include "Audio.h"
//#include "SD.h"
#include "FS.h"
#include "HTTPClient.h"
#include <ArduinoJson.h>

// Digital I/O used
#define SD_CS         10
#define SPI_MOSI      11
#define SPI_MISO      13
#define SPI_SCK       12
#define I2S_DOUT      41
#define I2S_BCLK      42
#define I2S_LRC       2

Audio audio;

String ssid =     "123456789";
String password = "qwert123";



////////////////////////////////////////////////////////////////////////////////////////////////////
// minimax ai大模型部分
String groupid = "1829130775476322636";
String api_key_id = "test24.9.21";
const char* apiKey = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiJ0dCIsIlVzZXJOYW1lIjoidHQiLCJBY2NvdW50IjoiIiwiU3ViamVjdElEIjoiMTgyOTEzMDc3NTQ4ODkwNTU0OCIsIlBob25lIjoiMTUzNDgyODc2MjciLCJHcm91cElEIjoiMTgyOTEzMDc3NTQ3NjMyMjYzNiIsIlBhZ2VOYW1lIjoiIiwiTWFpbCI6IiIsIkNyZWF0ZVRpbWUiOiIyMDI0LTA5LTIxIDEwOjUwOjMxIiwiaXNzIjoibWluaW1heCJ9.mR9cm4WYebQuTf8XjSeXaBvNMW9klXTmXlbcSpwCYf8Q00a4vwEpuxfWYkabuLOathD2zL4xWj3CqGbURFJs8U4_BM3P3VAg46Ac4qLdYcvGFr-mVrvtcLjwgTxK9DK989L8nJdGQPNo4AoTkMwNAXD8MaFVoVquK1i3VTRuPcCyUtX6XZwN_RdBT_3U-RqGFcc-nKkBI6Ffb-M8_fpHYIBQ_OlOov6sDJYG6sYSY5p0DAUC9PRZ4bTgM3HxfvkRErBL9vsk3Q1aPuJOIwzZRnnFqyzfSGl8Evb3oeWJf-AvgRpmKg10ghdXRpgwp0jlHkfloWxhtyTek9JtL13Dvw";
const char *tts_url = "https://api.minimax.chat/v1/t2a_pro?GroupId=1829130775476322636";
const char *chat_url = "https://api.minimax.chat/v1/text/chatcompletion_v2";
String mini_token_key = String("Bearer ") + apiKey;


//chatgpt对话
String getGPTAnswer(String inputText) {
  HTTPClient http1;
  http1.begin(chat_url);
  http1.addHeader("Content-Type", "application/json");
  http1.addHeader("Authorization", mini_token_key);
  String payload = "{\"model\":\"abab6.5s-chat\",\"messages\":[{\"role\": \"system\",\"content\": \"你是小小怪的生活助手机器人，要求下面的回答严格控制在256字符以内。\"},{\"role\": \"user\",\"content\": \"" + inputText + "\"}]}";
  int httpResponseCode = http1.POST(payload);
  String response;
  if (httpResponseCode == 200) {
    response = http1.getString();
    http1.end();
    DynamicJsonDocument jsonDoc(1024);
    Serial.println(response);
    deserializeJson(jsonDoc, response);
    String answer = jsonDoc["choices"][0]["message"]["content"];
    return answer;
  } else {
    // http1.end();
    response = http1.getString();
    http1.end();
    Serial.println(response);
    Serial.printf("chatError %i \n", httpResponseCode);
    return "error";
  }
}


//minimax TTS
String minimax_get_audio(String ouputText){
HTTPClient http2;
http2.begin(tts_url);
  http2.addHeader("Content-Type", "application/json");
  http2.addHeader("Authorization", mini_token_key);
  // 创建一个StaticJsonDocument对象，足够大以存储JSON数据
  StaticJsonDocument<200> doc;
  // 填充数据
  doc["text"] = ouputText;
  doc["model"] = "speech-02";
  doc["audio_sample_rate"] = 32000;
  doc["bitrate"] = 128000;
  doc["voice_id"] = "qiaopi_mengmei";//俏皮萌妹
  // 创建一个String对象来存储序列化后的JSON字符串
  String jsonString;
  // 序列化JSON到String对象
  serializeJson(doc, jsonString);
  int httpResponseCode = http2.POST(jsonString);
  if (httpResponseCode == 200) {
    String response = http2.getString();
    Serial.println(response);
    http2.end();
    DynamicJsonDocument jsonDoc(1024);
    deserializeJson(jsonDoc, response);
    String aduiourl = jsonDoc["audio_file"];
    return aduiourl;
  } else {
    Serial.printf("tts %i \n", httpResponseCode);
    http2.end();
    return "error";
  }

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




void music_sd_init() {
    //pinMode(SD_CS, OUTPUT);      digitalWrite(SD_CS, HIGH);
    //SPI.begin(SPI_SCK, SPI_MISO, SPI_MOSI);
    //Serial.begin(115200);
    //SD.begin(SD_CS);
    WiFi.disconnect();
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid.c_str(), password.c_str());
    while (WiFi.status() != WL_CONNECTED) delay(1500);
    audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
    //audio.setAudioTaskCore(0);//设置在核心0执行任务
    audio.setVolume(18); // default 0...21
//  or alternative
//  audio.setVolumeSteps(64); // max 255
//  audio.setVolume(63);    
//
//  *** radio streams ***
//    audio.connecttohost("http://stream.antennethueringen.de/live/aac-64/stream.antennethueringen.de/"); // aac
//  audio.connecttohost("http://mcrscast.mcr.iol.pt/cidadefm");                                         // mp3
//  audio.connecttohost("http://www.wdr.de/wdrlive/media/einslive.m3u");                                // m3u
//  audio.connecttohost("https://stream.srg-ssr.ch/rsp/aacp_48.asx");                                   // asx
//  audio.connecttohost("http://tuner.classical102.com/listen.pls");                                    // pls
//  audio.connecttohost("http://stream.radioparadise.com/flac");                                        // flac
//  audio.connecttohost("http://stream.sing-sing-bis.org:8000/singsingFlac");                           // flac (ogg)
//  audio.connecttohost("http://s1.knixx.fm:5347/dein_webradio_vbr.opus");                              // opus (ogg)
//  audio.connecttohost("http://stream2.dancewave.online:8080/dance.ogg");                              // vorbis (ogg)
//  audio.connecttohost("http://26373.live.streamtheworld.com:3690/XHQQ_FMAAC/HLSTS/playlist.m3u8");    // HLS
//  audio.connecttohost("http://eldoradolive02.akamaized.net/hls/live/2043453/eldorado/master.m3u8");   // HLS (ts)
//  *** web files ***
//  audio.connecttohost("https://github.com/schreibfaul1/ESP32-audioI2S/raw/master/additional_info/Testfiles/Pink-Panther.wav");        // wav
//  audio.connecttohost("https://github.com/schreibfaul1/ESP32-audioI2S/raw/master/additional_info/Testfiles/Santiano-Wellerman.flac"); // flac
//  audio.connecttohost("https://music.163.com/song/media/outer/url?id=381858.mp3");        // mp3
  audio.connecttohost(minimax_get_audio("你好呀，主人！我是你的小助手，小小怪下士。网络连接成功").c_str());
//  audio.connecttohost("https://github.com/schreibfaul1/ESP32-audioI2S/raw/master/additional_info/Testfiles/Miss-Marple.m4a");         // m4a (aac)
//  audio.connecttohost("https://github.com/schreibfaul1/ESP32-audioI2S/raw/master/additional_info/Testfiles/Collide.ogg");             // vorbis
//  audio.connecttohost("https://github.com/schreibfaul1/ESP32-audioI2S/raw/master/additional_info/Testfiles/sample.opus");             // opus
//  *** local files ***
//   audio.connecttoFS(SD, "/music/LDH - The days we passed together.mp3");     // SD
//  audio.connecttoFS(SD_MMC, "/test.wav"); // SD_MMC
//  audio.connecttoFS(SPIFFS, "/test.wav"); // SPIFFS

//  audio.connecttospeech("Wenn die Hunde schlafen, kann der Wolf gut Schafe stehlen.", "de"); // Google TTS
 
}

void music_loop()
{
    audio.loop();
}

// optional
void audio_info(const char *info){
    Serial.print("info        "); Serial.println(info);
}
void audio_id3data(const char *info){  //id3 metadata
    Serial.print("id3data     ");Serial.println(info);
}
void audio_eof_mp3(const char *info){  //end of file
    Serial.print("eof_mp3     ");Serial.println(info);
}
void audio_showstation(const char *info){
    Serial.print("station     ");Serial.println(info);
}
void audio_showstreamtitle(const char *info){
    Serial.print("streamtitle ");Serial.println(info);
}
void audio_bitrate(const char *info){
    Serial.print("bitrate     ");Serial.println(info);
}
void audio_commercial(const char *info){  //duration in sec
    Serial.print("commercial  ");Serial.println(info);
}
void audio_icyurl(const char *info){  //homepage
    Serial.print("icyurl      ");Serial.println(info);
}
void audio_lasthost(const char *info){  //stream URL played
    Serial.print("lasthost    ");Serial.println(info);
}
void audio_eof_speech(const char *info){
    Serial.print("eof_speech  ");Serial.println(info);
}


















